import axios from 'axios'
import { Message } from 'element-ui';
import {ENV} from '@/ENV'

export default function request(url, dataObj = {}, method = 'get') {
    let myPromise = {};
        url=ENV+url;
    /**
     * 设置token
     */
    axios.interceptors.request.use(config => {
        let token = localStorage.getItem('Authorization')
        if (token) {
            config.headers.Authorization = `${token}`
        }
        return config
    })
     /**
     * 判断身份信息是否过期
     */
    axios.interceptors.response.use(response => {
        return response
    }, err => {
        Message.error((err.response && err.response.data.message) || err.toString());
        if (err.response && err.response.status === 401) {
            setTimeout(() => {
                window.location.href = '/'
            }, 1000);
        }
    })
    //判断发起的请求类型
    switch (method.toLocaleLowerCase()) {
        case 'get':
            myPromise = new Promise((resolve, reject) => {
                axios.get(url, { params: dataObj }).then(response => {
                    resolve(response);
                })
            })
            break;
        case 'post':
            myPromise = new Promise((resolve, reject) => {
                axios.post(url, dataObj).then(response => {
                    resolve(response)
                })
            })
            break;
        case 'put':
            myPromise = new Promise((resolve, reject) => {
                axios.put(url, dataObj).then(response => {
                    resolve(response)
                })
            })
            break;
        case 'delete':
            myPromise = new Promise((resolve, reject) => {
                axios.delete(url, { data: dataObj }).then(response => {
                    resolve(response)
                })
            })
            break;
        case 'patch':
            myPromise = new Promise((resolve, reject) => {
                axios.patch(url, dataObj).then(response => {
                    resolve(response)
                })
            })
            break;
        default:
            break;
    }
    return myPromise
}